const express = require('express');
const router = express.Router();
const roleModel = require('../../models/role');
const { Op } = require('sequelize');
const { createSuccessResponse } = require('../../middleware/responseHandler.js');

// 获取角色列表
router.post('/getRoleList', async (req, res) => {
    try {
        const {
            page = 1,
            pageSize = 10,
            search = '',
            sortBy = 'role_id',
            sortOrder = 'DESC',
            group_name = '',
            role_level = '',
            is_formal = ''
        } = req.body;

        const where = {
            is_delete: 0
        };

        // 搜索条件
        if (search) {
            where[Op.or] = [
                { name_en: { [Op.like]: `%${search}%` } },
                { name_cn: { [Op.like]: `%${search}%` } },
                { identify_code: { [Op.like]: `%${search}%` } }
            ];
        }

        if (group_name) {
            where.group_name = group_name;
        }

        if (role_level !== '') {
            where.role_level = role_level;
        }

        if (is_formal !== '') {
            where.is_formal = is_formal;
        }

        const offset = (page - 1) * pageSize;
        const order = [[sortBy, sortOrder.toUpperCase()]];

        const { count, rows } = await roleModel.findAndCountAll({
            where,
            order,
            limit: parseInt(pageSize),
            offset: parseInt(offset)
        });

        res.json(createSuccessResponse({
            list: rows,
            total: count,
            page: parseInt(page),
            pageSize: parseInt(pageSize),
            totalPages: Math.ceil(count / pageSize)
        }, '获取角色列表成功'));
    } catch (error) {
        console.error('获取角色列表错误:', error);
        res.status(500).json({
            code: 500,
            message: '获取角色列表失败',
            error: error.message
        });
    }
});

// 获取角色详情
router.post('/getRoleById', async (req, res) => {
    try {
        const { role_id } = req.body;

        if (!role_id) {
            return res.status(400).json({
                code: 400,
                message: '角色ID不能为空'
            });
        }

        const role = await roleModel.findOne({
            where: {
                role_id: parseInt(role_id),
                is_delete: 0
            }
        });

        if (!role) {
            return res.status(404).json({
                code: 404,
                message: '角色不存在'
            });
        }

        res.json(createSuccessResponse(role, '获取角色详情成功'));
    } catch (error) {
        console.error('获取角色详情错误:', error);
        res.status(500).json({
            code: 500,
            message: '获取角色详情失败',
            error: error.message
        });
    }
});

// 创建角色
router.post('/createRole', async (req, res) => {
    try {
        const {
            identify_code,
            role_level,
            name_en,
            name_cn,
            icon_id = 0,
            icon_url = '',
            parent_id = 0,
            group_name,
            is_formal = 0
        } = req.body;

        // 验证必填字段
        if (!name_en || !name_cn || !group_name) {
            return res.status(400).json({
                code: 400,
                message: '角色英文名、中文名和分组名称不能为空'
            });
        }

        // 检查英文名是否已存在
        const existingRole = await roleModel.findOne({
            where: {
                name_en,
                is_delete: 0
            }
        });

        if (existingRole) {
            return res.status(400).json({
                code: 400,
                message: '角色英文名已存在'
            });
        }

        // 验证角色等级
        if (role_level > 255) {
            return res.status(400).json({
                code: 400,
                message: '角色等级不能超过255'
            });
        }

        const currentTime = Math.floor(Date.now() / 1000);

        const newRole = await roleModel.create({
            identify_code: identify_code || '',
            role_level: role_level || 0,
            name_en,
            name_cn,
            icon_id,
            icon_url,
            parent_id,
            group_name,
            is_formal,
            create_time: currentTime,
            update_time: currentTime
        });

        res.json(createSuccessResponse(newRole, '创建角色成功'));
    } catch (error) {
        console.error('创建角色错误:', error);
        res.status(500).json({
            code: 500,
            message: '创建角色失败',
            error: error.message
        });
    }
});

// 更新角色
router.post('/updateRole', async (req, res) => {
    try {
        const {
            role_id,
            identify_code,
            role_level,
            name_en,
            name_cn,
            icon_id,
            icon_url,
            parent_id,
            group_name,
            is_formal
        } = req.body;

        if (!role_id) {
            return res.status(400).json({
                code: 400,
                message: '角色ID不能为空'
            });
        }

        const role = await roleModel.findOne({
            where: {
                role_id: parseInt(role_id),
                is_delete: 0
            }
        });

        if (!role) {
            return res.status(404).json({
                code: 404,
                message: '角色不存在'
            });
        }

        // 如果更新英文名，检查是否与其他角色重复
        if (name_en && name_en !== role.name_en) {
            const existingRole = await roleModel.findOne({
                where: {
                    name_en,
                    role_id: { [Op.ne]: parseInt(role_id) },
                    is_delete: 0
                }
            });

            if (existingRole) {
                return res.status(400).json({
                    code: 400,
                    message: '角色英文名已存在'
                });
            }
        }

        // 验证角色等级
        if (role_level !== undefined && role_level > 255) {
            return res.status(400).json({
                code: 400,
                message: '角色等级不能超过255'
            });
        }

        const updateData = {};
        if (identify_code !== undefined) updateData.identify_code = identify_code;
        if (role_level !== undefined) updateData.role_level = role_level;
        if (name_en !== undefined) updateData.name_en = name_en;
        if (name_cn !== undefined) updateData.name_cn = name_cn;
        if (icon_id !== undefined) updateData.icon_id = icon_id;
        if (icon_url !== undefined) updateData.icon_url = icon_url;
        if (parent_id !== undefined) updateData.parent_id = parent_id;
        if (group_name !== undefined) updateData.group_name = group_name;
        if (is_formal !== undefined) updateData.is_formal = is_formal;

        updateData.update_time = Math.floor(Date.now() / 1000);

        await role.update(updateData);

        res.json(createSuccessResponse(role, '更新角色成功'));
    } catch (error) {
        console.error('更新角色错误:', error);
        res.status(500).json({
            code: 500,
            message: '更新角色失败',
            error: error.message
        });
    }
});

// 删除角色
router.post('/deleteRole', async (req, res) => {
    try {
        const { role_id } = req.body;

        if (!role_id) {
            return res.status(400).json({
                code: 400,
                message: '角色ID不能为空'
            });
        }

        const role = await roleModel.findOne({
            where: {
                role_id: parseInt(role_id),
                is_delete: 0
            }
        });

        if (!role) {
            return res.status(404).json({
                code: 404,
                message: '角色不存在'
            });
        }

        // 检查是否有子角色
        const childRoles = await roleModel.count({
            where: {
                parent_id: parseInt(role_id),
                is_delete: 0
            }
        });

        if (childRoles > 0) {
            return res.status(400).json({
                code: 400,
                message: '该角色下有子角色，无法删除'
            });
        }

        await role.update({
            is_delete: 1,
            update_time: Math.floor(Date.now() / 1000)
        });

        res.json(createSuccessResponse(null, '删除角色成功'));
    } catch (error) {
        console.error('删除角色错误:', error);
        res.status(500).json({
            code: 500,
            message: '删除角色失败',
            error: error.message
        });
    }
});

// 获取角色分组列表
router.post('/getRoleGroups', async (req, res) => {
    try {
        const groups = await roleModel.findAll({
            attributes: ['group_name'],
            where: {
                is_delete: 0
            },
            group: ['group_name'],
            raw: true
        });

        const groupList = groups.map(item => item.group_name);

        res.json(createSuccessResponse(groupList, '获取角色分组成功'));
    } catch (error) {
        console.error('获取角色分组错误:', error);
        res.status(500).json({
            code: 500,
            message: '获取角色分组失败',
            error: error.message
        });
    }
});

// 获取角色树结构
router.post('/getRoleTree', async (req, res) => {
    try {
        const roles = await roleModel.findAll({
            where: {
                is_delete: 0
            },
            order: [['role_id', 'ASC']],
            raw: true
        });

        // 构建树结构
        const buildTree = (parentId = 0) => {
            return roles
                .filter(role => role.parent_id === parentId)
                .map(role => ({
                    ...role,
                    children: buildTree(role.role_id)
                }));
        };

        const roleTree = buildTree();

        res.json(createSuccessResponse(roleTree, '获取角色树成功'));
    } catch (error) {
        console.error('获取角色树错误:', error);
        res.status(500).json({
            code: 500,
            message: '获取角色树失败',
            error: error.message
        });
    }
});

module.exports = router;